#! /bin/sh
set -e # Exit immediately if a command exits with a non-zero status.
# 获取操作系统类型
os_type=$(uname -s)
echo "os_type: $os_type"
# 操作系统不是Linux退出
if [ "$os_type" != "Linux" ]; then
    echo "This script only supports Linux"
    exit 1
fi
# 获取CPU架构
arch=$(uname -m)
echo "CPU架构: $arch"
# 根据CPU架构生成下载地址参数
if [ "$arch" = "x86_64" ]; then
    arch="amd64"
elif [ "$arch" = "i386" ]; then
    arch="386"
elif [ "$arch" = "i686" ]; then
    arch="386"
elif [ "$arch" = "aarch64" ]; then
    arch="arm64"
elif [ "$arch" = "armv7l" ]; then
    arch="arm"
else
    echo "Unsupported CPU architecture: $arch"
    exit 1
fi
echo "CPU架构: $arch"
# 获取脚本所在目录
SCRIPT_DIR=$(
    cd $(dirname $0)
    pwd
)
echo "应用安装目录: $SCRIPT_DIR"
# 判断当前用户是否为root，不是则退出
if [ $(id -u) != "0" ]; then
    echo "Error: You must be root to run this script, please use root to install, you can use the command: sudo -i to login root user"
    echo "Error: 请使用root用户运行,你可以使用命令: sudo -i 切换到root用户."

    exit 1
fi
# 下载config-deliver-client安装文件
curl -L -o $SCRIPT_DIR/config-deliver-client https://hjmcloud.gitee.io/config-deliver-client-release/linux_$arch/config-deliver-client
# 设置config-deliver-client可执行权限
chmod +x $SCRIPT_DIR/config-deliver-client
# 判断config.yaml文件是否存在
if [ ! -f "$SCRIPT_DIR/config.yaml" ]; then
    echo "config.yaml文件不存在"
    # 写入config.yaml文件
    cat >$SCRIPT_DIR/config.yaml <<EOF
logger:
  level: "info" 
  stdout: true 

apiServer: https://config.lidong.xin/getconfig # api server address
tasks:
  - name: "5472E3F6-37DE-B9A0-899C-39838E8C1336" # 任务名称
    file: "*" # 文件名
    corn: "@every 24h" # corn表达式
    localDir: "./localDir/5472E3F6-37DE-B9A0-899C-39838E8C1336" # 本地目录
    isRunOnStart: true # 是否启动时执行一次
EOF
fi
# 安装为系统服务
# 写入config-deliver-client.service文件
cat >/etc/systemd/system/config-deliver-client.service <<EOF
[Unit]
Description=Config Deliver Client
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=$SCRIPT_DIR
ExecStart=$SCRIPT_DIR/config-deliver-client
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
# 加载服务
systemctl daemon-reload
# 注册服务
systemctl enable config-deliver-client.service
# 启动服务
systemctl start config-deliver-client.service
# 查看服务状态
systemctl status config-deliver-client.service
